package club.jdiy.admin.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class GlobalInterceptor implements HandlerInterceptor {
    private final List<Integer> errorCodeList = Arrays.asList(404, 403, 500, 501);

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object arg2, ModelAndView view) {
        if (view != null && !view.isEmpty())
            view.getModelMap().put("_", "" + System.currentTimeMillis());
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
        if (errorCodeList.contains(response.getStatus()) && !"1".equals(request.getAttribute("isJumpToErrorPaged"))) {
            request.setAttribute("isJumpToErrorPaged", "1");
            String s = "/etc/error/" + response.getStatus();
            request.getRequestDispatcher(s).forward(request, response);
            return false;
        }
        //#######设置cookies变量以便freemarker用
        Map<String, String> cookies = new HashMap<>();
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                cookies.put(cookie.getName(), cookie.getValue());
            }
        }
        request.setAttribute("cookies", cookies);
        //#######设置cookies变量以便freemarker用
        return true;
    }
}